package com.pioneer.cloudstorage.controller;

import com.pioneer.cloudstorage.common.constant.JwtClaimsConstant;
import com.pioneer.cloudstorage.pojo.dto.UserDTO;
import com.pioneer.cloudstorage.pojo.entity.Result;
import com.pioneer.cloudstorage.pojo.entity.User;
import com.pioneer.cloudstorage.pojo.vo.UserInfoVO;
import com.pioneer.cloudstorage.service.UsersService;
import com.pioneer.cloudstorage.utils.JwtProperties;
import com.pioneer.cloudstorage.utils.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/api/auth")
public class Users {
    @Autowired
    private UsersService usersService;
    @Autowired
    private JwtProperties jwtProperties;
    @PostMapping("/register")
    public Result register(@RequestBody UserDTO userDTO) {
        log.info("用户注册");
        usersService.register(userDTO);
        return Result.success();
    }
    @PostMapping("/login")
    public Result login(@RequestBody UserDTO userDTO) {
        log.info("用户登录");
        User user =usersService.login(userDTO);
        //登录成功后，生成jwt令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.USER_ID, user.getId());
        String token = JwtUtil.createJWT(
                jwtProperties.getUserSecretKey(),
                jwtProperties.getUserTtl(),
                claims);
        return Result.success(token);
    }
    @GetMapping("/info")
    public Result info() {
        log.info("获取用户信息");
       UserInfoVO userInfoVO = usersService.info();
        return Result.success(userInfoVO);
    }
}
